package cn.touna.jss.modules.third.taobao;

import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.risk.api.utils.IntfTypeUtil;
import cn.touna.jss.common.cache.HbaseComponent;
import cn.touna.jss.common.entity.CreditQueryRequest;
import cn.touna.jss.common.mq.KafkaComponent;
import cn.touna.jss.common.properties.disconf.TaobaoProperties;
import cn.touna.jss.common.util.IPUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.callback.controller.JxlCallbackController;
import cn.touna.jss.modules.third.geo.util.HttpUtils;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.utils.ServiceContext;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * author: xl
 * time: 2018/11/15 17:05
 * description:
 **/
@RestController
public class TaobaoService {


    private static final Logger logger = LogManager.getLogger(JxlCallbackController.class);


    @Autowired
    private KafkaComponent kafkaComponent;

    @Autowired
    private HbaseComponent hbaseComponent;

    @Autowired
    TaobaoProperties taobaoProperties;


    @ApiMapping(value = "taobao.shujumohe", desc = "淘宝.数据魔盒")
    public Response shujumohe(JSONObject jsonObject) {
        logger.info("taobao.shujumohe req:{}", jsonObject);
        Response response = new Response();
        String taskId = jsonObject.getString("taskId");
        if (StringUtils.isEmpty(taskId)) {
            return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL.getErrorCode(), "请输入taskid");
        }
        try {
            String result = getResult(taskId, "account_info");
            JSONObject resultJson = JSONObject.parseObject(result);
            int code = resultJson.getInteger("code");
            String msg = resultJson.getString("message");
            if (code != 0) {
                return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL.getErrorCode(), msg);
            }
            return response.success(resultJson);
        } catch (Exception e) {
            logger.error("taobao.shujumohe is exception:{}", e.getMessage());
            return response.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL);
        }

    }


    private String getResult(String taskId, String task_module) {
        String url = taobaoProperties.getUrl() + "partner_code=" + taobaoProperties.getPartnerCode() + "&partner_key=" + taobaoProperties.getPartnerKey();
        Map map = new HashMap();
        map.put("task_id", taskId);
        if (!StringUtils.isEmpty(task_module)) {
            map.put("task_module", task_module);
        }
        String result = HttpUtils.sendPost(url, map);
        logger.info("taobao.shujumohe result:{}", result);
        return result;
    }


    @RequestMapping(value = "/crs/callBackTaobaoReport", method = {RequestMethod.POST})
    public JSONObject callBackTaobaoReport(HttpServletRequest request) {
        JSONObject resultJson = new JSONObject();
        try {
            String ip = IPUtil.getClientIP(request);
            String notifyType = request.getParameter("notify_type");
            String notifyEvent = request.getParameter("notify_event");
            if (notifyType.equals("ACQUIRE") && notifyEvent.equals("SUCCESS")) {
                String notify_data = request.getParameter("notify_data");
                logger.info("REQ【淘宝数据魔盒报告回调】 callBackTaobaoReport 访问ip地址:{}, notify_data:{}",ip, notify_data);
                JSONObject jsonObject = JSONObject.parseObject(notify_data);
                String taskId = jsonObject.getString("task_id");
                String result = getResult(taskId, null);
                JSONObject data = JSONObject.parseObject(result);
                JSONObject resultData = data.getJSONObject("data");
                int code = data.getInteger("code");
                String msg = data.getString("message");
                if (code == 0) {
                    saveHbaseData(data,resultData);
                }
                resultJson.put("code", 0);
                resultJson.put("message", "请求成功");
            }
            return resultJson;
        } catch (Exception e) {
            logger.error("taobao callbakck exception:{} ", e.getCause());
            resultJson.put("code", 1);
            resultJson.put("message", "未知错误异常");
        }
        return resultJson;
    }


    private void saveHbaseData(JSONObject data,JSONObject resultData ){
        Response taobaoResponse = new Response();
        String mobile = resultData.getString("user_mobile");
        String idCard = resultData.getString("identity_code");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mobile",mobile);
        jsonObject.put("idCard",idCard);
        CreditQueryRequest creditQueryRequest = new CreditQueryRequest();
        creditQueryRequest.setCrNo(ServiceContext.genUniqueId());
        creditQueryRequest.setIdCard(idCard);
        creditQueryRequest.setMobile(mobile);
        creditQueryRequest.setParams(jsonObject);
        creditQueryRequest.setMethod("taobao.shujumohe");
        taobaoResponse.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC, data);
        StringBuffer sb = new StringBuffer();
        sb.append(new StringBuffer(mobile).reverse().toString() + ":");
        sb.append(IntfTypeUtil.splitIntfType(creditQueryRequest.getMethod())[0]).append(":").append(IntfTypeUtil.splitIntfType(creditQueryRequest.getMethod())[1]).toString();
        //写入hbase
        hbaseComponent.saveCacheData(creditQueryRequest, taobaoResponse, sb.toString()); //写入hbase
        //结果推送给变量系统
        kafkaComponent.sendSyncCallData(creditQueryRequest, taobaoResponse);
        logger.info("PRO 调用【淘宝数据魔盒回调-callBackJxlReportData】发送kafka写入hbase mobile:{}",mobile);
    }




}
